<template>
<el-card shadow="never">
  <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="article-form">
    <h3>{{ isEdit ? '发布信息' : '编辑信息' }}</h3>
    <el-form-item label="信息标题" prop="messageTitle">
      <el-input v-model="form.messageTitle" placeholder="请输入信息标题" />
    </el-form-item>
    <!-- 富文本编辑器 -->
    <el-form-item label="信息内容" prop="messageContext">
      <!-- <ArtWangEditor class="el-top" ref="artWangEditorRef" /> -->
      <Tinymce v-model="content" />
    </el-form-item>
    <el-form-item label="信息标签" prop="messageGambit">
      <div class="tags-container">
        <el-tag v-for="tag in tags" :key="tag" class="tag-item" closable @close="handleClose(tag)">
          {{ tag }}
        </el-tag>
        <el-input
          v-if="inputVisible"
          ref="InputRef"
          v-model="inputValue"
          class="tag-input"
          size="small"
          @keyup.enter="handleInputConfirm"
          @blur="handleInputConfirm"
        />
        <el-button v-else class="button-new-tag" size="small" @click="showInput">
          <el-icon>
            <Plus />
          </el-icon>
          添加标签
        </el-button>
      </div>
    </el-form-item>

    <el-form-item label="信息分类" prop="menuId">
      <el-cascader
        v-model="menuId"
        :options="options"
        :props="props"
        @change="handleChange"
        popper-class="custom-cascader-popper"
      />
    </el-form-item>

    <el-form-item label="信息摘要" prop="messageDigest">
      <el-input
        v-model="form.messageDigest"
        type="textarea"
        :rows="3"
        placeholder="请输入信息摘要，将显示在信息列表中"
      />
    </el-form-item>

    <el-form-item label="封面图片" prop="messageShowImg">
      <div class="w-full">
        <MyUpload :file-list="fileList" @deleteFile="deleteFile" @uploadFileSuccess="success" />
      </div>
    </el-form-item>
    <el-col :span="24">
      <el-form-item label="附件图片">
        <div class="w-full">
          <MyUpload
            :file-list="fileInfo"
            @deleteFile="fileInfoDeleteFile"
            @uploadFileSuccess="fileInfoSuccess"
          />
        </div>
      </el-form-item>
    </el-col>

    <div class="pulishInfo">
      <div>
        <h3>发布平台</h3>
        <el-checkbox-group v-model="strategyType">
          <el-checkbox label="官网" :value="1"></el-checkbox>
          <el-checkbox label="抖音" :value="2"></el-checkbox>
        </el-checkbox-group>
      </div>
    </div>

    <div class="flex justify-end">
      <el-button @click="goBack">取消</el-button>
      <el-button type="primary" @click="pulishArticle" v-loading="loading" :disabled="loading"
        >发布
      </el-button>
    </div>
  </el-form>
</el-card>
</template>
<script setup lang="ts">
  import { ref, reactive, computed, onMounted } from 'vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { useWorktabStore } from '@/store/modules/worktab'
  import {
    authGetLoginUserUsingPost,
    scenicMessageGetMessageInfoByIdUsingPost,
    scenicMessageSaveMessagePushUsingPost,
    scenicMessageUpdateMessagePushUsingPost,
    scenicWebsiteQueryWebsiteMenuInfoUsingGet
  } from '@/api/4a'
  import { useRoute, useRouter } from 'vue-router'
  import { watch } from 'vue'
  import Tinymce from '@/components/tinymce/index.vue'
  import { useUserStore } from '@/store/modules/user'
  const userStore = useUserStore()
  const userInfo = computed(() => userStore.getUserInfo)

  const router = useRouter()
  const route = useRoute()
  const worktabStore = useWorktabStore()
  const isEdit = ref(true)
  const articleId = ref<string>(route.query.id ? String(route.query.id) : '')
  const formRef = ref<FormInstance>()
  const inputVisible = ref(false)
  const inputValue = ref('')
  const InputRef = ref()
  const loading = ref(false)
  const editorHtml = ref('') // 编辑器内容
  let tags = ref<string[]>([]) // 标签
  const menuId = ref([])
  const strategyType = ref()
  const options = ref([])
  let id = ref('')
  const props = {
    expandTrigger: 'hover' as const,
    checkStrictly: true
  }

  const initForm = reactive({
    fileInfo: '[]', // 附件信息
    id: undefined,
    imgAuthorId: '', // 图片作者ID
    messageAuthorId: '', // 作者ID
    messageEditId: '', // 编辑ID
    messageAuditId: '', // 审核ID
    messageTitle: '', // 信息标题
    messageDigest: '', // 信息摘要
    messageShowImg: '[]', // 封面图片
    messageContext: '', // 信息内容
    messageGambit: '', // 信息标签
    sendDeptNameId: '(0)', // 出品部门ID
    sendTime: '', // 发布时间
    showType: 1, // 展示类型【1信息详情】
    messageStrategyBoList: [
      {
        browseCount: 0,
        id: undefined,
        sendStatus: 2,
        strategyParam: '',
        strategyType: 1,
        websiteMenuMessageBoList: [
          {
            menuId: 1,
            messageId: undefined,
            orderNum: 1,
            websiteId: 1
          }
        ]
      }
    ]
  })
  // 表单数据 xiaoxituisongcelvebo
  const form = reactive({ ...initForm })

  //   const artWangEditorRef = ref()
  const content = ref('')

  // 将(武汉)(体育) 改成 ["武汉","体育"]
  const processTagsWithBrackets = (tagString: string): string[] => {
    if (!tagString) return []
    // 匹配括号中的内容
    const regex = /\(([^)]+)\)/g
    const matches = tagString.match(regex)
    if (!matches) return [tagString]
    // 提取括号中的内容
    return matches.map((tag) => tag.slice(1, -1))
  }

  // 获取信息详情
  const getArticleDetail = async () => {
    scenicMessageGetMessageInfoByIdUsingPost({
      params: {
        messageId: articleId.value
      }
    }).then((res) => {
      Object.assign(form, res.data)
      //   artWangEditorRef.value.setHtml(res.data?.messageContext)
      content.value = res.data?.messageContext
      nextTick(() => {
        formRef.value?.validateField('messageContext')
      })
      // 绑定菜单id
      menuId.value = form.messageStrategyBoList[0].websiteMenuMessageBoList[0].menuId
      tags.value = form.messageGambit ? processTagsWithBrackets(res.data?.messageGambit) : []
      strategyType.value = form.messageStrategyBoList[0].strategyType
        ? [form.messageStrategyBoList[0].strategyType]
        : [1]
      // 安全地处理文件列表数据
      try {
        form.messageShowImg = res.data?.messageShowImg || '[]'
        if (typeof form.messageShowImg === 'string') {
          const parsed = JSON.parse(form.messageShowImg)
          if (!Array.isArray(parsed)) {
            form.messageShowImg = '[]'
          }
        }
      } catch (e) {
        console.warn('文件列表数据格式错误:', e)
        form.messageShowImg = '[]'
      }
    })
  }

  // 封面图片
  const fileList = computed({
    get() {
      try {
        return JSON.parse(form.messageShowImg || '[]')
      } catch {
        return '[]'
      }
    },
    set(value) {
      form.messageShowImg = value
    }
  })

  const success = (a) => {
    fileList.value.push(a.data)
    fileList.value = JSON.stringify(fileList.value)
    formRef.value?.validateField('messageShowImg')
  }

  const deleteFile = (params) => {
    fileList.value = JSON.stringify(fileList.value.filter((item) => item.path !== params.path))
    formRef.value?.validateField('messageShowImg')
  }

  // 附件图片
  const fileInfo = computed({
    get() {
      try {
        return JSON.parse(form.fileInfo || '[]')
      } catch {
        return []
      }
    },
    set(value) {
      form.fileInfo = value
    }
  })

  const fileInfoSuccess = (a) => {
    fileInfo.value.push(a.data)
    fileInfo.value = JSON.stringify(fileInfo.value)
  }

  const fileInfoDeleteFile = (params) => {
    fileInfo.value = JSON.stringify(fileInfo.value.filter((item) => item.path !== params.path))
  }
  // 返回列表
  const goBack = () => {
    Object.assign(form, initForm) // 清空表单
    tags.value = [] // 清空标签
    fileList.value = '[]' // 清空主图
    fileInfo.value = '[]' // 清空附件图
    worktabStore.removeTab(route.path)
    router.replace('/article/article-list')
  }

  // 表单验证规则
  const rules = reactive<FormRules>({
    messageTitle: [
      { required: true, message: '请输入信息标题', trigger: 'blur' },
      { min: 2, max: 100, message: '标题长度应在2-100个字符之间', trigger: 'blur' }
    ],
    messageDigest: [
      { required: true, message: '请输入信息摘要', trigger: 'blur' },
      { min: 10, max: 500, message: '摘要长度应在10-500个字符之间', trigger: 'blur' }
    ],
    messageShowImg: [
      { required: true, message: '请选择封面图片', trigger: 'change' },
      {
        validator: (rule, value) => {
          let list = []

          try {
            list = typeof value === 'string' ? JSON.parse(value) : value
          } catch {
            list = []
          }

          if (!Array.isArray(list) || list.length === 0) {
            throw new Error('请上传至少一张封面图片')
          }

          return Promise.resolve()
        },
        trigger: 'change'
      }
    ],
    messageContext: [
      {
        required: true,
        message: '请输入信息内容',
        trigger: 'blur'
      },
      {
        validator: (rule, value) => {
          if (isEditorContentEmpty(value)) {
            throw new Error('内容不能为空')
          }
          return Promise.resolve()
        },
        trigger: 'change'
      }
    ],
    sendTime: [{ required: true, message: '请选择发布时间', trigger: 'change' }],
    showType: [{ required: true, message: '请选择展示类型', trigger: 'change' }],
    messageStrategyBoList: [{ required: true, message: '请选择发布策略', trigger: 'change' }],
    messageGambit: [{ required: true, message: '请输入信息标签', trigger: 'change' }]
  })

  // 标签相关方法
  const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
      InputRef.value?.input?.focus()
    })
  }
  const handleInputConfirm = () => {
    if (typeof inputValue.value === 'string' && inputValue.value.trim()) {
      if (!tags.value.includes(inputValue.value)) {
        tags.value.push(inputValue.value)
      }
    }
    inputVisible.value = false
    inputValue.value = ''

    // 同步更新 messageGambit
    form.messageGambit = tags.value.map((tag) => `(${tag})`).join('')
    // 手动触发验证
    formRef.value?.validateField('messageGambit')
  }

  // 删除标签
  const handleClose = (tag: string) => {
    const index = tags.value.indexOf(tag)
    if (index > -1) {
      tags.value.splice(index, 1)
    }
    // 同步更新 messageGambit
    form.messageGambit = tags.value.map((tag) => `(${tag})`).join('')
    // 手动触发验证
    formRef.value?.validateField('messageGambit')
  }

  // 格式化事件
  const formDate = (date: string | Date): string => {
    return useDateFormat(date, 'YYYYMMDDHHmmss').value
  }

  // 信息分类
  const handleChange = () => {
    if (!menuId.value.length) {
      ElMessage.error('请选择信息分类')
    } else if (menuId.value.length === 2) {
      form.messageStrategyBoList[0].websiteMenuMessageBoList[0].menuId = menuId.value[1]
    } else {
      form.messageStrategyBoList[0].websiteMenuMessageBoList[0].menuId = menuId.value[0]
    }
  }
  // 获取当前登录人的信息
  // const getUserInfo = async () => {
  //   await authGetLoginUserUsingPost({}).then((res) => {
  //     let userId = res.data?.id
  //     if (userId) {
  //       id.value = `${userId}`
  //       form.imgAuthorId = `${userId}` // 图片作者ID
  //       form.messageAuthorId = `${userId}` // 作者ID 
  //       form.messageAuditId = `${userId}` // 审核ID
  //     }
  //   })
  // }

  // 获取官网相关菜单
  const getWebsiteList = async () => {
    const res = await scenicWebsiteQueryWebsiteMenuInfoUsingGet({
      params: {
        id: 1
      }
    })
    if (res.code === 0) {
      const menuList = res.data?.websiteMenuVoList || []
      options.value = buildCascaderOptions(menuList)
    }
  }
  const buildCascaderOptions = (data) => {
    return data.map((item) => ({
      value: item.id,
      label: item.menuName,
      children: item.children ? buildCascaderOptions(item.children) : undefined
    }))
  }

  // 修改路由监听逻辑
  watch(
    () => route.query.id,
    (newValue) => {
      if (newValue) {
        articleId.value = String(newValue) // 确保ID始终是字符串类型
        if(route.path === '/article/article-publish'){
          getArticleDetail()
        }
        isEdit.value = false
      } else {
        articleId.value = ''
        Object.assign(form, initForm)
        isEdit.value = true
        editorHtml.value = ''
        tags.value = []
        menuId.value = []
      }
    },
    { immediate: true }
  )
  onMounted(() => {
    // getUserInfo()
    getWebsiteList().then(() => {
      // 确保在组件挂载时根据路由参数决定是否重置
      if (!route.query.id) {
        Object.assign(form, initForm)
      }
    })
  })

  // 添加信息
  const pulishArticle = async () => {
    form.imgAuthorId = userInfo.value.id
    form.messageAuthorId = userInfo.value.id
    form.messageAuditId = userInfo.value.id
    form.messageContext = content.value
    // 表单验证
    if (!formRef.value) return
    try {
      await formRef.value.validate()
      loading.value = true
      //   initForm.messageContext = artWangEditorRef.value.getHtml()
      initForm.messageContext = content.value
      //   const html = artWangEditorRef.value.getHtml()
      const html = content.value

      if (!route.query.id) {
        scenicMessageSaveMessagePushUsingPost({
          body: {
            ...form,
            messageGambit: tags.value.map((tag) => `(${tag})`).join('') || '',
            messageContext: html,
            messageStrategyBoList: [
              {
                ...form.messageStrategyBoList[0],
                strategyParam: JSON.stringify(
                  form.messageStrategyBoList[0].websiteMenuMessageBoList[0]
                )
              }
            ],
            sendTime: formDate(new Date())
          }
        })
          .then((res) => {
            if (res.code === 0) {
              ElMessage.success('发布成功')
              router.push({ path: '/article/article-list' })
            } else {
              ElMessage.error('发布失败')
            }
          })
          .finally(() => {
            loading.value = false
          })
      } else {
        scenicMessageUpdateMessagePushUsingPost({
          body: {
            ...form,
            messageContext: html,
            messageGambit: tags.value.map((tag) => `(${tag})`).join('') || '',
            messageStrategyBoList: [
              {
                ...form.messageStrategyBoList[0],
                strategyParam: JSON.stringify(
                  form.messageStrategyBoList[0].websiteMenuMessageBoList[0]
                )
              }
            ]
          }
        })
          .then((res) => {
            if (res.code === 0) {
              ElMessage.success('修改成功')
              router.push({ path: '/article/article-list' })
            } else {
              ElMessage.error('修改失败')
            }
          })
          .finally(() => {
            loading.value = false
          })
      }
    } catch (error) {
      console.error('表单验证失败', error)
      ElMessage.error('请完善表单信息')
    }
  }

  // const messageContextTouched = ref(false)

  function isEditorContentEmpty(content: string): boolean {
    if (!content) return true
    const text = content.replace(/<[^>]*>/g, '').trim()
    return text === ''
  }
</script>

<style lang="scss" scoped>
  .article-form {
    // max-height: 60vh;
    padding-right: 20px;
    overflow-y: auto;

    h3 {
      margin-top: 10px;
    }
  }

  .editor {
    p {
      margin-top: 5px;
      margin-left: 10px;
      font-size: 14px;
    }
  }

  .cover-uploader {
    :deep(.el-upload) {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 178px;
      height: 178px;
      overflow: hidden;
      cursor: pointer;
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }

  :deep(.custom-cascader-popper) {
    z-index: 9999 !important;
  }

  :deep(.wangeditor) {
    z-index: 1000; // 确保低于 cascader 的 z-index
  }

  :deep(.el-form-item--large .el-form-item__content) {
    position: relative;
    z-index: 1;
  }

  .el-form-item {
    margin-top: 15px;
  }

  .article-category {
    display: flex;
  }

  .category-form-item {
    width: 20rem;
  }

  .cover-uploader-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 178px;
    height: 178px;
    font-size: 28px;
    color: #8c939d;
    text-align: center;
  }

  .cover-image {
    display: block;
    width: 178px;
    height: 178px;
    object-fit: cover;
  }

  .upload-tip {
    margin-top: 8px;
    font-size: 12px;
    color: #999;
  }

  .tags-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
    min-height: 32px;
    padding: 4px;
    background-color: var(--el-fill-color-blank);
    border: 1px solid var(--el-border-color);
    border-radius: 4px;
    transition: all 0.3s;

    &:hover {
      border-color: var(--el-color-primary);
    }

    .tag-item {
      margin: 0;
      color: var(--el-color-primary);
      background-color: var(--el-color-primary-light-9);
      border-color: var(--el-color-primary-light-7);
      transition: all 0.3s;

      &:hover {
        background-color: var(--el-color-primary-light-8);
      }
    }

    .tag-input {
      width: 120px;
      margin: 0;
      vertical-align: middle;
    }

    .button-new-tag {
      display: flex;
      align-items: center;
      height: 32px;
      padding: 0 12px;
      margin: 0;
      color: var(--el-color-primary);
      background-color: var(--el-color-primary-light-9);
      border-color: var(--el-color-primary-light-7);
      transition: all 0.3s;

      .el-icon {
        margin-right: 4px;
      }

      &:hover {
        color: var(--el-color-primary);
        background-color: var(--el-color-primary-light-8);
        border-color: var(--el-color-primary-light-6);
      }
    }
  }

  .pulishInfo {
    margin-top: 20px;
  }
  .el-card{
    border-radius: 8px !important;
    margin-bottom: 20px !important;
  }
</style>
